<?php

//defineste un Client care va folosi programul; 
//in functie de ce alege va avea mai multi sau mai putini useri

	define('CT_NR_LUNI_GRATUITE', '2');

class Client {
	public $id_client;			//id-ul din tabel
	public $admin_user_id;		//id-ul userului administrator (cel care a inregistrat firma)
	public $nume;
	public $cf;					//cod fiscal
	public $rc;					//registru comert
	public $max_useri;
	public $activ;
	public $vizibil;
	public $ciclu_plata;
	public $tel_fix;
	public $tel_fax;
	public $tel_mobil;
	public $email;
	public $web;
    public $tip_abon;
	public $client_reducere;     // Reducere pt clientii e-transport.ro si altii;
	public $pret;
	public $moneda;				//Moneda in care face plata
	public $testat;				//Daca a trecut luna de testare sau nu
	public $data_inreg;
	public $client_cnp;
	public $client_serie_ci;
	public $factura_nume;
	public $factura_cnp;
	public $factura_serie_ci;
    public $adresa;             //adaugat doar acuma....
	public $conturi = array();	
	
	public $rau_platnic; 
	
	function __construct($nume, $cf, $rc, $max_useri, $activ, $vizibil, $ciclu_plata, $tel_fix, $tel_fax
								,$tel_mobil, $email, $web, $tip_abon, $client_reducere, $pret, $moneda, $testat, $data_inreg, $client_cnp, $client_serie_ci
								,$factura_nume, $factura_cnp, $factura_serie_ci) {
		$this->id_client = CT_NOT_SAVED_YET;
		$this->nume 			= $nume;								
		$this->cf 				= $cf;								
		$this->rc 				= $rc;
		$this->max_useri 		= $max_useri;								
		$this->activ 			= $activ;								
		$this->vizibil 			= $vizibil;								
		$this->ciclu_plata 		= $ciclu_plata;				

		$this->tel_fix 			= $tel_fix;								
		$this->tel_fax 			= $tel_fax;								
		$this->tel_mobil 		= $tel_mobil;								
		$this->email 			= $email;								
		$this->web 				= $web;								
        $this->tip_abon         = $tip_abon;                                
		$this->client_reducere 	= $client_reducere;
		$this->pret 			= $pret;								
		$this->moneda 			= $moneda;								
		$this->testat 			= $testat;			
		$this->admin_user_id = 0;					
        
        if ($data_inreg == '')
            $this->data_inreg = date("Y-m-d");
		else
            $this->data_inreg = $data_inreg;
		$this->client_cnp = $client_cnp;
		$this->client_serie_ci = $client_serie_ci;
		$this->factura_nume = $factura_nume;
		$this->factura_cnp = $factura_cnp;
		$this->factura_serie_ci = $factura_serie_ci;
		$this->client_reducere = CT_ABONAMENT_NEREDUS;
		$this->adresa = new Address(CT_ADRESA_CLIENT, '', '', '', '', '', '');													
	}
	
	public function get_admin_user_id() {
		return $this->admin_user_id;	
	}
	
	public function queryInsert($db, $user = null) {
		
	  	$query = $db->prepare("INSERT INTO `client`  ( 		`nume` , 				`cf` , 
															`rc` , 					`max_useri`,
	                        		        				`activ` ,    			`vizibil` , 
		                        	        				`ciclu_plata` , 	 
		                                					`tel_fix` ,  			`tel_fax`,
		                                					`tel_mobil` ,			`email`,
		                                					`web` ,					`tip_abon`,  `client_reducere`,
		                                					`pret` ,				`moneda`,
		                                					`testat` ,				`data_inreg`,
		                                					`client_cnp` ,			`client_serie_ci`,
		                                					`factura_nume` ,		`factura_cnp`,
		                                					`factura_serie_ci`,		`admin_user_id`		                           
		                               					)		                               					 
		            				VALUES  (				:nume,  			:cf, 
	            											:rc,   				:max_useri, 
	                      									:activ,   			:vizibil, 
		                      								:ciclu_plata,	
		                      								:tel_fix, 			:tel_fax,
		                      								:tel_mobil, 		:email,
		                                					:web ,				:tip_abon, :client_reducere,
		                      								:pret, 				:moneda,
		                      								:testat, 			:data_inreg,
		                      								:client_cnp, 		:client_serie_ci,
		                      								:factura_nume, 		:factura_cnp,
		                      								:factura_serie_ci,  :admin_user_id
		                      			)");
		

		$query->bindParam(':nume', 			($this->nume));
		$query->bindParam(':cf', 			($this->cf));
		$query->bindParam(':rc', 			($this->rc));
		$query->bindParam(':max_useri', 	($this->max_useri));
		$query->bindParam(':activ', 		($this->activ));
		$query->bindParam(':vizibil', 		($this->vizibil));
		$query->bindParam(':ciclu_plata', 	($this->ciclu_plata));

		$query->bindParam(':tel_fix', 		($this->tel_fix));
		$query->bindParam(':tel_fax', 		($this->tel_fax));
		$query->bindParam(':tel_mobil', 	($this->tel_mobil));
        $query->bindParam(':tip_abon',         ($this->tip_abon));
		$query->bindParam(':client_reducere', 		($this->client_reducere));
		$query->bindParam(':email', 		($this->email));
		$query->bindParam(':web', 			($this->web));		
		$query->bindParam(':pret', 			($this->pret));
		$query->bindParam(':moneda', 		($this->moneda));
		$query->bindParam(':testat', 		($this->testat));
		$query->bindParam(':data_inreg', 	($this->data_inreg));
		$query->bindParam(':client_cnp', 	($this->client_cnp));
		$query->bindParam(':client_serie_ci', 	($this->client_serie_ci));
		$query->bindParam(':factura_nume', 	($this->factura_nume));
		$query->bindParam(':factura_cnp', 	($this->factura_cnp));
		$query->bindParam(':factura_serie_ci', 	($this->factura_serie_ci));

		try {  		
			$db->beginTransaction();

			//acum inserez userul
			if (isset($user)) $user_id = $user->queryInsert($db);	
			// pus aici pentru a putea avea totul intr-o tranzactie!
			$query->bindParam(':admin_user_id', ($user_id));
			
			if ($query->execute() === FALSE) {
				$errInfo = $query->errorInfo();
				$errInfo = $errInfo[2];
				$query->closeCursor();
				throw new QueryInsertClientException("Error inserting client " . $this->nume . $errInfo);
			}
							
			$this->id_client = (int) $db->lastInsertId();	
			$this->adresa->id_owner = $this->id_client;
			$this->adresa->queryInsertAddress($db);
			$query->closeCursor();

  			//inserarea conturilor
	  		for ($i = 0; $i < count($this->conturi); $i++) {
	  			//completam campul de id_owner la conturi pentru ca la creearea de client nou acest camp nu se stie pana cand
	  			//nu se face insertul proproiu-zis cu datele clientului
	  			$this->conturi[$i]->id_owner = $this->id_client;
	  			$this->conturi[$i]->queryInsertCont($db);	 			
	  		}	  		
  			//end inserarea conturilor  

	  		//acum inseram o linie goala doar cu id_client setat in tabelul setari_client
	  		$setari = new SetariClient($this->id_client, null, null, null, CT_ZILE_SCADENTA_SOL, CT_ZILE_SCADENTA_EXEC, CT_ZILE_ALARMA_PLATI, CT_ZILE_SCADENTA_INCASARI);
	  		$setari->queryInsertSetariClient($db);
	  		
  			$db->commit();
		}	
		catch (QueryInsertUserException $e) {				
			$db->rollBack();
			$query->closeCursor();
            throw new QueryInsertClientException("Failed saving client user to the database" . $errInfo);			
			// redirectOnError(CT_ADD_EDIT_CLIENT_INSERT_USER);
		}		
  		catch (QueryInsertClientException $e) {
			$db->rollBack();
			$query->closeCursor();
			throw new QueryInsertClientException("Failed saving client to the database" . $errInfo);
		}
		catch (QueryInsertAddressException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertClientException("Failed saving client to the database! reason: address" . $errInfo);
		}
		catch (QueryInsertContException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertClientException("Failed saving client to the database! reason: cont" . $errInfo);
		}
		catch (QueryInsertSetariException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertClientException("Failed saving client to the database! reason: setari_client" . $errInfo);			
		}
  		
		return $this->id_client; 		//return the client's id
	}
	
	public function queryUpdate($db) {
		$query = $db->prepare("UPDATE `client`  
								SET  	`nume` = :nume, 				`cf` = :cf, 
										`rc` = :rc, 					`max_useri` = :max_useri,
        		        				`activ` = :activ,    			`vizibil` = :vizibil, 
            	        				`ciclu_plata` = :ciclu_plata, 		
                    					`tel_fix` = :tel_fix ,  			`tel_fax` = :tel_fax,
                    					`tel_mobil` = :tel_mobil ,			`email` = :email,
                    					`web` = :web ,					`tip_abon` = :tip_abon,  `client_reducere` = :client_reducere,
                    					`pret` = :pret ,				`moneda` = :moneda,
                    					`testat` = :testat,				`data_inreg` = :data_inreg,
                    					`client_cnp` = :client_cnp,		`client_serie_ci` = :client_serie_ci,
                    					`factura_nume` = :factura_nume,	`factura_cnp` = :factura_cnp,
                    					`factura_serie_ci` = :factura_serie_ci, `admin_user_id` = :admin_user_id
                    			WHERE id = :id_client
            					");
				
		$query->bindParam(':nume', 			($this->nume));
		$query->bindParam(':cf', 			($this->cf));
		$query->bindParam(':rc', 			($this->rc));
		$query->bindParam(':max_useri', 	($this->max_useri));
		
		$query->bindParam(':activ', 		($this->activ));
		$query->bindParam(':vizibil', 		($this->vizibil));
		$query->bindParam(':ciclu_plata', 	($this->ciclu_plata));

		$query->bindParam(':tel_fix', 		($this->tel_fix));
		$query->bindParam(':tel_fax', 		($this->tel_fax));
		$query->bindParam(':tel_mobil', 	($this->tel_mobil));
		$query->bindParam(':email', 		($this->email));
		$query->bindParam(':web', 			($this->web));
        $query->bindParam(':tip_abon',         ($this->tip_abon));
		$query->bindParam(':client_reducere', 		($this->client_reducere));
		$query->bindParam(':pret', 			($this->pret));
		$query->bindParam(':moneda', 		($this->moneda));
		$query->bindParam(':testat', 		($this->testat));
		$query->bindParam(':data_inreg', 	($this->data_inreg));
		$query->bindParam(':client_cnp', 	($this->client_cnp));
		$query->bindParam(':client_serie_ci', 	($this->client_serie_ci));
		$query->bindParam(':factura_nume', 	($this->factura_nume));
		$query->bindParam(':factura_cnp', 	($this->factura_cnp));
		$query->bindParam(':factura_serie_ci', 	($this->factura_serie_ci));
		$query->bindParam(':admin_user_id', ($this->admin_user_id));
		$query->bindParam(':id_client', 	($this->id_client));
		
		try {  		
			$db->beginTransaction();
		
			if ($query->execute() === FALSE) {
				$errInfo = $query->errorInfo();
				$errInfo = $errInfo[2];
				$query->closeCursor();
				throw new QueryUpdateClientException("Error updating client " . $this->nume . $errInfo);
			}
			
			$this->adresa->queryUpdateAddress($db);
			$query->closeCursor();	
			
			//update la conturi in functie de statusul fiecarui cont  	
  					
  			for ($i = 0; $i < count($this->conturi); $i++) {  			
  				if ($this->conturi[$i]->status == CT_CONT_MODIFIED) 
  					$this->conturi[$i]->queryUpdate($db);  				
  				  			
	  			if ($this->conturi[$i]->status == CT_CONT_NEW) 
	  				$this->conturi[$i]->queryInsertCont($db);
	  			
  				if ($this->conturi[$i]->status == CT_CONT_DELETED) 
  					$this->conturi[$i]->queryDeleteCont($db);  			
  			}
  			$db->commit();
		}
		catch (QueryUpdateClientException $e) {
			$db->rollBack();		
			$query->closeCursor();
        	throw new QueryUpdateClientException("UPDATE - Failed updating client with id: " . $this->id_client . $errInfo);
		}
		catch (QueryUpdateAddressException $e) {
			$db->rollBack();		
			$query->closeCursor();
        	throw new QueryUpdateClientException("ADDRESS - Failed updating client with id: " . $this->id_client . $errInfo);
		}		
		catch (QueryUpdateContException $e) {
			$db->rollBack();		
			$query->closeCursor();			
        	throw new QueryUpdateClientException("CONT - Failed updating client with id: " . $this->id_client . $errInfo);
		}
		catch (QueryInsertContException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateClientException("INSERT - Failed updating client with id: " . $this->id_client . $errInfo);
		}
		catch (QueryDeleteContException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateClientException("DELETE CONT - Failed updating client with id: " . $this->id_client . $errInfo);
		}
		
		return CT_RESULT_OK;
	}
	
  	public static function queryLoad($db, $id_client) {
        $query = $db->prepare("SELECT *
                    			FROM client
                    			WHERE id = :id_client");
        
        $query->bindParam(':id_client', $id_client);

        if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
            $query->closeCursor();
        	throw new QueryLoadClientException("Failed loading client with id " . $id_client . $errInfo);            
        }
            
        $data = $query->fetch(PDO::FETCH_ASSOC);
        
        if (!isset($data['id'])) {
        	$query->closeCursor();
        	throw new QueryLoadClientException("Failed loading client with id " . $id_client . " reason: id not existing");            
        }
        $query->closeCursor();
        
        $client = new Client($data['nume'], $data['cf'], $data['rc'], $data['max_useri'], $data['activ'], $data['vizibil'], $data['ciclu_plata']
        						, $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email']
        						, $data['web'], $data['tip_abon'], $data['client_reducere'], $data['pret'], $data['moneda'], $data['testat'], $data['data_inreg']
        						, $data['client_cnp'], $data['client_serie_ci'], $data['factura_nume'], $data['factura_cnp'], $data['factura_serie_ci']);
		        						
        $client->id_client = (int) $data['id'];
        $client->data_inreg = $data['data_inreg'];
        $client->admin_user_id = $data['admin_user_id'];
        
        //verific acuma daca clientul este rau platnic
        
        $query_rau_platnic = "SELECT DATEDIFF(data_sfarsit, CURDATE()) AS nr_zile_dif, achitat
        						FROM factura_client 
        						WHERE id_client = $id_client
        						ORDER BY id DESC
        						LIMIT 1";

  		if (($result_rau_platnic = $db->query($query_rau_platnic)) === FALSE) {						
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];
           	throw new QueryDetermineRauPlatnicException("Nu am putut determina informatia despre factuare pentru client cu id" . $id_client);
		}
		$data_rau_platnic = $result_rau_platnic->fetch(PDO::FETCH_ASSOC);
		
		if (empty($data_rau_platnic)) {

			//inseamna ca clientul e proaspat inregistrat si nu are nici o plata inregistrata
			//perioada de gratie 2 luni
			//inainte cu 15 zile sa se termine cele 2 luni il anuntam ca are de plata
			//odata ce a trecut cele 15 zile si nu a platit il anuntam ca daca nu plateste se va termina
			//folosirea programului
			//dupa aceste 15 zile daca nu a platit il vom redirecta doar la facturare atunci cand se logheaza
        	
			$query2 = "SELECT DATEDIFF(CURDATE(), data_inreg) AS nr_zile_dif2
        						FROM client 
        						WHERE id = $id_client";
	
	  		if (($result2 = $db->query($query2)) === FALSE) {						
	            $errInfo = $db->errorInfo();
	            $errInfo = $errInfo[2];
	           	throw new QueryDetermineRauPlatnicException("Nu am putut determina informatia despre facutare pentru client cu id" . $id_client);
			}
			$data2 = $result2->fetch(PDO::FETCH_ASSOC);

			if (($data2['nr_zile_dif2'] > (60 - 15)) && $data2['nr_zile_dif2'] <= 60) {
				//inseamna ca a depasit cele 2 luni de gratuitate si a intrat in cele 15 zile de prima
				//avertizare
				$client->rau_platnic = CT_RAU_PLATNIC_1;
			}
			else if ($data2['nr_zile_dif2'] > 60 && $data2['nr_zile_dif2'] <= 75) {
				//au trecut cele 2 luni cu avertizarea din ultimele 15 zile si nu a platit nimic
				//intram in avertizarea de tip 2
				$client->rau_platnic = CT_RAU_PLATNIC_2;
			}
			else if ($data2['nr_zile_dif2'] > 75) $client->rau_platnic = CT_RAU_PLATNIC_BLOCK;
			else $client->rau_platnic = CT_RAU_PLATNIC_FALSE;
        						
		}
		else if (isset($data_rau_platnic) && !empty($data_rau_platnic)) {  
			//inseamna ca clientul are cel putin o plata inregistrata fie ea validata sau nu

			if ($data_rau_platnic['achitat'] == CT_FACTURA_NEACHITATA) {
//				var_dump($data_rau_platnic['nr_zile_dif']);
//				die();
				if (
		        	$data_rau_platnic['nr_zile_dif'] >= 0 && 
		        	$data_rau_platnic['nr_zile_dif'] <= 15) $client->rau_platnic = CT_RAU_PLATNIC_2;
		        else if 
		        	($data_rau_platnic['nr_zile_dif'] < 0 && 
		        	 $data_rau_platnic['nr_zile_dif'] >= -15) $client->rau_platnic = CT_RAU_PLATNIC_1;
				else if 	        	
					($data_rau_platnic['nr_zile_dif'] > 15) $client->rau_platnic = CT_RAU_PLATNIC_BLOCK; 	        	 
		        else $client->rau_platnic = CT_RAU_PLATNIC_FALSE;	

//		        var_dump($client->rau_platnic);
			}
			else {
				$client->rau_platnic = CT_RAU_PLATNIC_FALSE;
			}	        
		}
		else  {
			$client->rau_platnic = CT_RAU_PLATNIC_FALSE;			
		}

        // incarcare adresa
        
        try {
        	$address = Address::queryLoadByClient($db, $client->id_client);
        	$conturi = Cont::queryLoadContByOwner($db, CT_CONT_CLIENT, $id_client);        	
        }
        catch (QueryLoadAddressException $e) {
        	throw new QueryLoadAddressException("Failed loading address with for client with id " . $id_client);
        }
        catch (QueryLoadContException $e) {
        	throw new QueryLoadContException("Failed loading conturi for client with id " . $id_client);
        }
        $client->adresa = $address;         
        $client->conturi = $conturi; 
        
        return $client;
    }	
	
    function queryDelete($db) {
    // TODO: Trebuie vazut cum se face stergerea... trebuie sa fie sterse toate datele clientului daca se ajunge la asta...
      	$query = $db->prepare("DELETE FROM client WHERE id = :id_client");
      	$query->bindParam(':id_client', $this->id_client);
      	
      	if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
      		$query->closeCursor();
      		throw new QueryDeleteClientException("Failed deleting client with id: " . $this->id_client . $errInfo);
      	}
		$query->closeCursor();
      	Address::deleteAddressByIdOwner($db, $this->id_client, CT_ADRESA_CLIENT);
      	return CT_RESULT_OK;      	
    }
    
    //deletes a client by id; does not require an object.... STATIC
    public static function deleteClientById($db, $id_client) {
    // TODO: Trebuie vazut cum se face stergerea... trebuie sa fie sterse toate datele clientului daca se ajunge la asta...
    	$query = $db->prepare("DELETE FROM client WHERE id = :id_client");
    	$query->bindParam(':id_client', $id_client);
    	    	
      	if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
  			$query->closeCursor();
      		throw new QueryDeleteClientException("Failed deleting client with id: " . $id_client . $errInfo);
      	}
      	$query->closeCursor();
      	Address::deleteAddressByIdOwner($db, $this->id_client, CT_ADRESA_CLIENT);
  		return CT_RESULT_OK;      	
    }
    
    public static function get_perioada_plata($db, $id_client, $ciclu_plata) {
        $query = $db->prepare("SELECT data_sfarsit, DATE_ADD(data_sfarsit, INTERVAL $ciclu_plata MONTH) AS urm_data_scadenta
                                FROM factura_client 
                                WHERE id_client = $id_client
                                ORDER BY id DESC 
                                LIMIT 1"); 

        if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
            $query->closeCursor();
            throw new QueryCheckPerioadaPlataException("Failed getting perioada plata for client: " . $id_client . $errInfo);
        }

        $data = $query->fetch(PDO::FETCH_ASSOC);

        if (!empty($data) && ($data['data_sfarsit'])) {
            $date = array();
            $date[0] = $data['data_sfarsit'];
            $date[1] = $data['urm_data_scadenta'];
            return $date;
        }
        else {
        	
            $query = $db->prepare("SELECT DATE_ADD(data_inreg, INTERVAL 2 MONTH) AS data_scadenta, DATE_ADD(data_inreg, INTERVAL ($ciclu_plata + 2) MONTH) AS urm_data_scadenta
                                        FROM client 
                                        WHERE id = $id_client;"); 
            if ($query->execute() === FALSE) {
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
                $query->closeCursor();
                throw new QueryCheckPerioadaPlataException("Failed getting perioada plata for client: " . $id_client . $errInfo);
            }
            $data = $query->fetch(PDO::FETCH_ASSOC);
            $date = array();
            
            $date[0] = $data['data_scadenta'];
            $date[1] = $data['urm_data_scadenta'];

            return $date;
        }
    }
    
    public static function insert_plata_inca_neachitata($db, $id_client, $data_scadenta1, $data_scadenta2, $suma, $moneda) {
        try {
            $db->beginTransaction();
            
            $query = $db->prepare("SELECT nr_factura 
                                    FROM factura_client 
                                    ORDER BY id DESC 
                                    LIMIT 1"); 

            if ($query->execute() === FALSE) {
                $query->closeCursor();
                throw new QuerySelectingNrFacturaException("Failed selecting last nr_factura");
            }        
            $data = $query->fetch(PDO::FETCH_ASSOC);
            
            $nr_factura = $data['nr_factura'];
            $nr_facuta_fara_zero = str_replace("0", '', $nr_factura);        
            $nr_facuta_fara_zero++;
            
            $lungime_sir_zero = 6 - strlen($nr_facuta_fara_zero);
            $sir_zero = str_repeat("0", $lungime_sir_zero);
            $nr_factura = $sir_zero . $nr_facuta_fara_zero;

            $query_string = "INSERT INTO factura_client(
                                id_client, nr_factura, data, suma, moneda, 
                                achitat, data_inceput, data_sfarsit)
                                VALUES(" . 
                                ($id_client) . ", '" . ($nr_factura) . "', NOW(), " .  
                                ($suma) . ", " . $moneda . ", " . CT_FACTURA_NEACHITATA . ", '" . 
                                ($data_scadenta1) . "', '" . 
                                ($data_scadenta2) . "');";

            $query = $db->prepare($query_string); 
                    
            if ($query->execute() === FALSE) {
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
                $query->closeCursor();
                throw new QueryInsertFacturaException("Failed inserting factura for client: " . $id_client . $errInfo);
            }
            $query->closeCursor();        
            $db->commit();            
        }
        catch (QuerySelectingNrFacturaException $e) {
            $db->rollBack();
            throw new QueryInsertPlataNeachitataException("Failed inserting plata neachitata for client: " . $id_client) . $errInfo;
        }
        catch (QueryInsertFacturaException $e) {
            $db->rollBack();
            throw new QueryInsertPlataNeachitataException("Failed inserting plata neachitata for client: " . $id_client . $errInfo);
        }        
    }
    
    public static function determine_need_to_pay($db, $id_client) {

 		if ($_SESSION['client_logat']->rau_platnic == CT_RAU_PLATNIC_PENDING) return CT_RESULT_FALSE;
		if ($_SESSION['client_logat']->rau_platnic == CT_RAU_PLATNIC_1 ||
			$_SESSION['client_logat']->rau_platnic == CT_RAU_PLATNIC_2 ||
			$_SESSION['client_logat']->rau_platnic == CT_RAU_PLATNIC_BLOCK) {
			return CT_RESULT_OK;	                                
		}			
		else {
			//verificam daca e in perioada de proba cele 2 luni pentru a 
			//anunta frumos ca nu e nevoie de plata
	        $query_rau_platnic = "SELECT DATEDIFF(data_sfarsit, CURDATE()) AS nr_zile_dif, achitat
        						FROM factura_client 
        						WHERE id_client = $id_client
        						ORDER BY id DESC
        						LIMIT 1";

	  		if (($result_rau_platnic = $db->query($query_rau_platnic)) === FALSE) {						
	            $errInfo = $db->errorInfo();
	            $errInfo = $errInfo[2];
	           	throw new QueryDetermineRauPlatnicException("Nu am putut determina informatia despre facutare pentru client cu id" . $id_client);
			}
			$data_rau_platnic = $result_rau_platnic->fetch(PDO::FETCH_ASSOC);
		
			if (empty($data_rau_platnic)) 
				return CT_PERIOADA_PROBA;
			if (!empty($data_rau_platnic) && $data_rau_platnic['achitat'] == CT_FACTURA_NEACHITATA) 
				return CT_RESULT_FALSE; 			
			return CT_RESULT_FALSE;
		}
    }
    
    public static function getPlatiById($db, $id_client, $pagina, $per_pag) {
        $limit1 = $pagina * $per_pag;
        $query = $db->prepare("SELECT SQL_CALC_FOUND_ROWS *
                                FROM factura_client
                                WHERE id_client = :id_client
                                LIMIT $limit1, $per_pag");
        $query->bindParam(':id_client', $id_client);    
        
        if ($query->execute() === FALSE) {
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
            $query->closeCursor();
            throw new QueryGetPlatiByClientException("Failed loading facturi for client with id: " . $id_client . $errInfo);
        }
        $query2 = "SELECT FOUND_ROWS() AS total"; 
              
        if (($result2 = $db->query($query2)) === FALSE) {
               throw new QueryGetPlatiByClientException("Failed loading facturi for client with id: " . $id_client . $errInfo);
        }         
        
        $data2 = $result2->fetch(PDO::FETCH_ASSOC);
        $total = $data2['total'];   
             
        $plati = array();
        $poz = 1;
        while ($data = $query->fetch(PDO::FETCH_ASSOC)) {
            $plati[$poz]['id'] = $data['id'];
            $plati[$poz]['nr_factura'] = $data['nr_factura'];
            $plati[$poz]['data'] = $data['data'];
            $plati[$poz]['suma'] = $data['suma'];
            $plati[$poz]['moneda'] = $data['moneda'];
            $plati[$poz]['achitat'] = $data['achitat'];
            $plati[$poz]['data_inceput'] = $data['data_inceput'];
            $plati[$poz]['data_sfarsit'] = $data['data_sfarsit'];
            $poz++;
        }
        $plati[0]['total'] = $total;
        $query->closeCursor();        
        return $plati;    
    }
    
    public static function getUsersCount($db, $id_client) {
        $query = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id
                                FROM user
                                WHERE id_client = :id_client");
        $query->bindParam(':id_client', $id_client);    
        
        if ($query->execute() === FALSE) {
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
            $query->closeCursor();
            throw new QueryLoadClientException("Failed loading users count for client with id: " . $id_client . $errInfo);
        }
        $query2 = "SELECT FOUND_ROWS() AS total"; 
              
        if (($result2 = $db->query($query2)) === FALSE) {
               throw new QueryLoadClientException("Failed loading users count for client with id: " . $id_client . $errInfo);
        }         
        
        $data2 = $result2->fetch(PDO::FETCH_ASSOC);
        $total = $data2['total'];
        return $total;
    }
}       

?>